package com.feiyisuo.sso.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;


import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    GitEeAuthenticationUserService gitEeAuthenticationUserService;

    @Resource
    private OAuth2AuthenticationSuccessHandlerImpl oAuth2AuthenticationSuccessHandlerImpl;
    @Resource
    private OAuth2AuthenticationFailureHandlerImpl oAuth2AuthenticationFailureHandlerImpl;

    /**
     * Security configuration
     */
    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {

        // 禁用 CSRF 保护
        http.csrf().disable();

        // 允许任何跨域请求
        http.cors(c -> c.configurationSource(corsConfigurationSource()));

        //配置session
        http.sessionManagement(c -> c
                .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                .maximumSessions(5));

        // OAuth2 登录配置
        http.oauth2Login(c -> {
            //c.defaultSuccessUrl("http://localhost:8081/home", true);// 登录成功后重定向到前端
            c.redirectionEndpoint()
                    .baseUri("/login/oauth2/code/*");
            c.userInfoEndpoint(userInfo -> userInfo.userService(gitEeAuthenticationUserService));
            c.successHandler(oAuth2AuthenticationSuccessHandlerImpl);
            c.failureHandler(oAuth2AuthenticationFailureHandlerImpl);
        });

        return http.build();
    }

    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        //需要设置成自己的前端地址
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080", "https://127.0.0.1:8080")); // 显式列出允许的来源
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的方法
        configuration.setAllowCredentials(true); // 允许携带凭证
        //允许的请求头
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setExposedHeaders(List.of("Set-Cookie"));
        //不需要预检请求的时间
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}
